/**
 * 番茄时钟
 */

// const { ipcRenderer } = require('electron');
const { handleError } = require('../../common/error-handler');
const { showToast } = require('../../common/show-toast');

// 状态管理
const state = {
    pomodoroInterval: null,// 定时器
    fullscreenUpdateInterval: null, // 全屏模式下的更新定时器
    isPaused: false,// 是否暂停
    isFocus: true,  // 是否专注
    remainSeconds: 0,// 剩余秒数
    focusDuration: 25 * 60,// 专注时长
    breakDuration: 5 * 60,// 休息时长
    longBreakDuration: 15 * 60,// 长休息时长
    pomodorosUntilLongBreak: 4,// 多少个番茄后长休息
    completedPomodoros: 0,// 已完成的番茄数
    totalFocusTimeToday: 0,// 今日专注时间
    totalCompletedPomodoros: 0,// 总完成番茄数
    streakDays: 0,// 连续天数
    initialSeconds: 0,// 初始秒数
    lastCompletedDate: null,// 最后完成日期
    isUpTimer: false,// 是否正计时
    upTimerSeconds: 0,// 正计时秒数
    startTime: null,// 开始时间
    status: '等待开始',// 状态
    color: '#888'// 颜色
};

// DOM元素缓存
const DOM_ELEMENTS = {
    timer: document.getElementById('pomodoro-timer'),
    status: document.getElementById('pomodoro-status'),
    progressCircle: document.querySelector('.timer-circle-progress'),
    buttons: {
        start: document.getElementById('btn-start-pomodoro'),
        pause: document.getElementById('btn-pause-pomodoro'),
        stop: document.getElementById('btn-stop-pomodoro'),
        skip: document.getElementById('btn-skip-pomodoro'),
        upTimer: document.getElementById('btn-up-timer-pomodoro'),
        fullscreen: document.getElementById('btn-fullscreen-pomodoro')
    },
    inputs: {
        focus: document.getElementById('focus-duration'),
        break: document.getElementById('break-duration'),
        longBreak: document.getElementById('long-break-duration'),
        pomodorosUntilLongBreak: document.getElementById('pomodoros-until-long-break'),
        autoStartBreaks: document.getElementById('auto-start-breaks'),
        autoStartPomodoros: document.getElementById('auto-start-pomodoros'),
        notificationEnabled: document.getElementById('notification-enabled'),
        soundEnabled: document.getElementById('sound-enabled')
    },
    stats: {
        todayCompleted: document.getElementById('today-completed-count'),
        todayFocusTime: document.getElementById('today-focus-time'),
        totalCompleted: document.getElementById('total-completed-count'),
        streakDays: document.getElementById('streak-days')
    }
};

// 初始化番茄钟
function initPomodoro() {
    try {
        // 加载保存的统计数据
        loadPomodoroStats();

        // 绑定事件
        bindEvents();

        // 初始化显示
        updateDisplay();

        // 快捷时间按钮点击事件
        document.querySelectorAll('.btn-quick-time').forEach(button => {
            button.addEventListener('click', function () {
                const time = parseInt(this.getAttribute('data-time'), 10);
                const focusDurationInput = document.getElementById('focus-duration');

                // 更新输入框的值
                focusDurationInput.value = time;

                // 触发change事件，确保更新其他相关状态
                focusDurationInput.dispatchEvent(new Event('change'));

                // 更新活跃按钮状态
                document.querySelectorAll('.btn-quick-time').forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
            });
        });

        // 获取focus-duration输入框的值作为默认时长
        const focusDuration = document.getElementById('focus-duration').value;
        // 根据focus-duration的值选中对应的快捷按钮
        const defaultTimeBtn = document.querySelector(`.btn-quick-time[data-time="${focusDuration}"]`);
        if (defaultTimeBtn) {
            defaultTimeBtn.classList.add('active');
        }
        // 绑定时间输入控制按钮
        document.querySelectorAll('.time-control-btn').forEach(button => {
            button.addEventListener('click', () => {
                const input = button.parentElement.querySelector('input');
                const value = parseInt(input.value);
                const isIncrement = button.classList.contains('increment');
                const min = parseInt(input.min);
                const max = parseInt(input.max);

                input.value = Math.min(Math.max(
                    value + (isIncrement ? 1 : -1),
                    min
                ), max);

                // 触发change事件，确保更新state对象
                input.dispatchEvent(new Event('change'));
            });
        });

        // 请求通知权限
        if (Notification.permission !== 'granted') {
            Notification.requestPermission();
        }
    } catch (error) {
        handleError('初始化番茄钟失败', error);
    }
}

// 绑定事件
function bindEvents() {
    // 按钮事件
    DOM_ELEMENTS.buttons.start.onclick = startPomodoro;
    DOM_ELEMENTS.buttons.pause.onclick = pausePomodoro;
    DOM_ELEMENTS.buttons.stop.onclick = stopPomodoro;
    DOM_ELEMENTS.buttons.skip.onclick = skipPomodoro;
    DOM_ELEMENTS.buttons.upTimer.onclick = startUpTimer;
    DOM_ELEMENTS.buttons.fullscreen.onclick = toggleFullscreen;

    // 输入框事件
    DOM_ELEMENTS.inputs.focus.onchange = updateSettings;
    DOM_ELEMENTS.inputs.break.onchange = updateSettings;
    DOM_ELEMENTS.inputs.longBreak.onchange = updateSettings;
    DOM_ELEMENTS.inputs.pomodorosUntilLongBreak.onchange = updateSettings;
}

// 开始番茄钟
function startPomodoro() {
    if (state.isUpTimer) {
        showToast('请先停止正计时');
        return;
    }

    if (state.isPaused) {
        resumePomodoro();
        return;
    }

    state.isFocus = true;
    state.remainSeconds = state.focusDuration;
    state.initialSeconds = state.focusDuration;
    state.isPaused = false;
    state.status = '专注中...';
    state.color = '#e74c3c';
    state.startTime = new Date();

    startTimer();
    updateDisplay();
}

// 暂停番茄钟
function pausePomodoro() {
    if (!state.pomodoroInterval) return;

    state.isPaused = true;
    state.status = state.isFocus ? '专注已暂停' : '休息已暂停';
    state.color = '#888';

    clearInterval(state.pomodoroInterval);
    state.pomodoroInterval = null;
    updateDisplay();
}

// 恢复番茄钟
function resumePomodoro() {
    state.isPaused = false;
    state.status = state.isFocus ? '专注中...' : '休息中...';
    state.color = state.isFocus ? '#e74c3c' : '#2ecc71';

    startTimer();
    updateDisplay();
}

// 停止番茄钟
function stopPomodoro() {
    //如果大于一分钟才保存
    console.log('番茄完成>1分钟', state);
    if (state.focusDuration - state.remainSeconds >= 60 || state.upTimerSeconds >= 60) {
        let record = null;
        let duration = 0;
        if (state.isUpTimer) {// 正计时模式下更新正计时
             duration = state.upTimerSeconds;
            record = createPomodoroRecord(state.startTime, new Date(), duration, 'timeUp');
        } else {
             duration = state.focusDuration - state.remainSeconds;
            record = createPomodoroRecord(state.startTime, new Date(), duration, 'timeDown');
        }
        savePomodoroRecords(record);// 保存番茄记录
    }
    // 停止番茄钟
    clearInterval(state.pomodoroInterval);
    state.pomodoroInterval = null;
    state.isPaused = false;
    state.isUpTimer = false; // 重置正计时状态，确保可以切换回倒计时模式
    state.upTimerSeconds = 0; // 重置正计时秒数
    state.remainSeconds = state.focusDuration;
    state.initialSeconds = state.focusDuration;
    state.status = '等待开始';
    state.color = '#888';
    updateDisplay();
}

// 跳过当前番茄/休息
function skipPomodoro() {
    if (!state.pomodoroInterval) return;

    if (state.isFocus) {
        completePomodoro();
        startBreak();
    } else {
        startPomodoro();
    }
}

// 开始休息
function startBreak() {
    const isLongBreak = state.completedPomodoros % state.pomodorosUntilLongBreak === 0;
    state.remainSeconds = isLongBreak ? state.longBreakDuration : state.breakDuration;
    state.initialSeconds = state.remainSeconds;
    state.isFocus = false;
    state.status = isLongBreak ? '长休息中...' : '休息中...';
    state.color = isLongBreak ? '#3498db' : '#2ecc71';

    if (DOM_ELEMENTS.inputs.autoStartBreaks.checked) {
        startTimer();
    } else {
        pausePomodoro();
    }
    updateDisplay();
}

// 开始正计时
function startUpTimer() {
    if (state.pomodoroInterval && !state.isUpTimer) {
        showToast('请先停止番茄钟');
        return;
    }

    state.isUpTimer = true;
    state.upTimerSeconds = 0;
    state.startTime = new Date();
    state.status = '正计时中...';
    state.color = '#2ecc71';
    state.isPaused = false;

    startTimer();
    updateDisplay();
}

// 启动定时器
function startTimer() {
    if (state.pomodoroInterval) {
        clearInterval(state.pomodoroInterval);
    }

    state.pomodoroInterval = setInterval(() => {
        if (state.isUpTimer) {// 正计时模式下更新正计时
            updateUpTimer();
        } else {
            updateTimer();
        }
    }, 1000);
}

// 更新正计时
function updateUpTimer() {
    const now = new Date();
    state.upTimerSeconds = Math.floor((now - state.startTime) / 1000);
    updateDisplay();
}

// 更新倒计时
function updateTimer() {
    state.remainSeconds--;
    if (state.remainSeconds <= 0) {
        if (state.isFocus) {
            completePomodoro();
            startBreak();
        } else {
            if (DOM_ELEMENTS.inputs.autoStartPomodoros.checked) {
                startPomodoro();
            } else {
                stopPomodoro();
            }
        }
    }
    updateDisplay();
}

// 完成一个番茄
function completePomodoro() {
    state.completedPomodoros++;
    state.totalCompletedPomodoros++;
    state.totalFocusTimeToday += state.focusDuration;

    // 更新连续天数
    const today = new Date().toLocaleDateString();
    if (!state.lastCompletedDate) {
        state.streakDays = 1;
    } else if (state.lastCompletedDate !== today) {
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        if (state.lastCompletedDate === yesterday.toLocaleDateString()) {
            state.streakDays++;
        } else {
            state.streakDays = 1;
        }
    }
    state.lastCompletedDate = today;

    // 只有当计时超过1分钟时才保存统计数据
    if (state.focusDuration - state.remainSeconds >= 60) {
        console.log('番茄完成>1分钟', state);
        let record = null;
        let duration = 0;
        if (state.isUpTimer) {// 正计时模式下更新正计时
             duration = state.focusDuration - state.remainSeconds;
            record = createPomodoroRecord(state.startTime, new Date(), duration, 'timeUp');
        } else {
             duration = state.focusDuration - state.remainSeconds;
            record = createPomodoroRecord(state.startTime, new Date(), duration, 'timeDown');
        }
        savePomodoroRecords(record);// 保存番茄记录

    }
    
    
    savePomodoroStats();// 保存统计数据
    updateDisplay();
    sendNotification();
}

// 更新显示
function updateDisplay() {
    // 更新时间显示
    const timeText = state.isUpTimer
        ? formatTime(state.upTimerSeconds)
        : formatTime(state.remainSeconds);
    DOM_ELEMENTS.timer.textContent = timeText;

    // 更新状态
    DOM_ELEMENTS.status.textContent = state.status;
    DOM_ELEMENTS.status.style.color = state.color;

    // 更新进度条
    updateProgressCircle();

    // 更新统计
    updateStats();
}

// 更新进度圈
function updateProgressCircle() {
    const circle = DOM_ELEMENTS.progressCircle;
    if (state.isUpTimer) {
        circle.style.strokeDashoffset = '0';
    } else {
        const progress = (state.initialSeconds - state.remainSeconds) / state.initialSeconds;
        circle.style.strokeDashoffset = (1 - progress) * 283;
    }
    circle.style.stroke = state.color;
}

// 更新统计显示
function updateStats() {
    DOM_ELEMENTS.stats.todayCompleted.textContent = state.completedPomodoros;
    DOM_ELEMENTS.stats.todayFocusTime.textContent = `${Math.floor(state.totalFocusTimeToday / 60)}分钟`;
    DOM_ELEMENTS.stats.totalCompleted.textContent = state.totalCompletedPomodoros;
    DOM_ELEMENTS.stats.streakDays.textContent = state.streakDays;
}

// 格式化时间
function formatTime(seconds) {
    const min = Math.floor(seconds / 60);
    const sec = seconds % 60;
    return `${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
}

// 发送通知
function sendNotification() {
    if (!DOM_ELEMENTS.inputs.notificationEnabled.checked) return;

    const title = state.isFocus ? '休息时间到！' : '专注时间到！';
    const message = state.isFocus ? '该休息一下了！' : '开始新的番茄时间！';

    new Notification(title, { body: message });

    if (DOM_ELEMENTS.inputs.soundEnabled.checked) {
        playNotificationSound();
    }
}

// 播放提示音
function playNotificationSound() {
    // const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmojBTGH0fPTgjMGHm7A7+OZSA0PVqzn77BdGAg+ltryxnMpBSl+zPLaizsIGGS57OihUBELTKXh8bllHgU2jdXzzn0vBSF1xe/glEILElyx6OyrWBUIQ5zd8sFtJAUuhM/z1YU2Bhxqvu7mnEoODlOq5O+zYBoGPJTY8shWW1tcXmBjZmhrbG1tbW5w');
    // audio.play().catch(console.error);
}

// 切换全屏
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        fullscreenPomodoro();
    } else {
        exitFullscreen();
    }
}



// 全屏显示番茄钟
function fullscreenPomodoro() {
    try {
        // 创建全屏容器
        const fullscreenContainer = document.createElement('div');
        fullscreenContainer.className = 'pomodoro-fullscreen';

        // 添加计时器显示
        const timerContainer = document.createElement('div');
        timerContainer.className = 'timer-circle-container';

        const timerCircle = document.createElement('div');
        timerCircle.className = 'timer-circle';

        const timerDisplay = document.createElement('div');
        timerDisplay.id = 'fullscreen-pomodoro-timer'; // 使用不同的ID避免冲突
        if (state.isUpTimer) {
            const min = String(Math.floor(state.upTimerSeconds / 60)).padStart(2, '0');
            const sec = String(state.upTimerSeconds % 60).padStart(2, '0');
            timerDisplay.textContent = `${min}:${sec}`;
        } else {
            const min = String(Math.floor(state.remainSeconds / 60)).padStart(2, '0');
            const sec = String(state.remainSeconds % 60).padStart(2, '0');
            timerDisplay.textContent = `${min}:${sec}`;
        }

        const statusDisplay = document.createElement('div');
        statusDisplay.id = 'fullscreen-pomodoro-status'; // 使用不同的ID避免冲突
        if (state.isUpTimer) {
            statusDisplay.textContent = state.isPaused ? '正计时已暂停' : '正计时中...';
            statusDisplay.style.color = state.isPaused ? '#888' : '#28a745';
        } else {
            statusDisplay.textContent = state.isPaused ? '已暂停' : (state.isFocus ? '专注中...' : '休息中...');
            statusDisplay.style.color = state.isPaused ? '#888' : (state.isFocus ? '#e74c3c' : '#27ae60');
        }

        const svgNS = "http://www.w3.org/2000/svg";
        const svg = document.createElementNS(svgNS, "svg");
        svg.setAttribute('viewBox', '0 0 100 100');
        svg.classList.add('timer-svg');

        const circleBg = document.createElementNS(svgNS, "circle");
        circleBg.setAttribute('cx', '50');
        circleBg.setAttribute('cy', '50');
        circleBg.setAttribute('r', '45');
        circleBg.classList.add('timer-circle-bg');

        const circleProgress = document.createElementNS(svgNS, "circle");
        circleProgress.setAttribute('cx', '50');
        circleProgress.setAttribute('cy', '50');
        circleProgress.setAttribute('r', '45');
        circleProgress.classList.add('timer-circle-progress');

        // 设置进度
        const circumference = 2 * Math.PI * 45;
        if (state.isUpTimer) {
            circleProgress.style.stroke = '#28a745';
            circleProgress.style.strokeDashoffset = circumference;
        } else if (state.initialSeconds > 0) {
            const progressPercent = ((state.initialSeconds - state.remainSeconds) / state.initialSeconds) * 100;
            const dashoffset = circumference - (circumference * progressPercent / 100);
            circleProgress.style.strokeDashoffset = dashoffset;

            if (state.isFocus) {
                circleProgress.style.stroke = '#e74c3c';
            } else {
                circleProgress.style.stroke = '#27ae60';
            }
        }

        svg.appendChild(circleBg);
        svg.appendChild(circleProgress);

        timerCircle.appendChild(timerDisplay);
        timerCircle.appendChild(statusDisplay);
        timerCircle.appendChild(svg);

        timerContainer.appendChild(timerCircle);

        // 添加控制按钮
        const controlsContainer = document.createElement('div');
        controlsContainer.className = 'pomodoro-controls';

        const exitButton = document.createElement('button');
        exitButton.className = 'btn btn-primary';
        exitButton.innerHTML = '<i class="fas fa-compress"></i> 退出全屏';
        exitButton.onclick = exitFullscreen;

        controlsContainer.appendChild(exitButton);

        fullscreenContainer.appendChild(timerContainer);
        fullscreenContainer.appendChild(controlsContainer);

        document.body.appendChild(fullscreenContainer);

        // 设置全屏模式下的计时器更新
        // 每秒更新一次全屏模式下的时间显示
        if (state.fullscreenUpdateInterval) {
            clearInterval(state.fullscreenUpdateInterval);
        }

        state.fullscreenUpdateInterval = setInterval(() => {
            // 获取全屏模式下的计时器和状态显示元素
            const fullscreenTimer = document.getElementById('fullscreen-pomodoro-timer');
            const fullscreenStatus = document.getElementById('fullscreen-pomodoro-status');
            const fullscreenProgressCircle = fullscreenContainer.querySelector('.timer-circle-progress');

            if (fullscreenTimer && fullscreenStatus) {
                // 更新时间显示
                if (state.isUpTimer) {
                    const min = String(Math.floor(state.upTimerSeconds / 60)).padStart(2, '0');
                    const sec = String(state.upTimerSeconds % 60).padStart(2, '0');
                    fullscreenTimer.textContent = `${min}:${sec}`;
                } else {
                    const min = String(Math.floor(state.remainSeconds / 60)).padStart(2, '0');
                    const sec = String(state.remainSeconds % 60).padStart(2, '0');
                    fullscreenTimer.textContent = `${min}:${sec}`;
                }

                // 更新状态显示
                if (state.isUpTimer) {
                    fullscreenStatus.textContent = state.isPaused ? '正计时已暂停' : '正计时中...';
                    fullscreenStatus.style.color = state.isPaused ? '#888' : '#28a745';
                } else {
                    fullscreenStatus.textContent = state.isPaused ? '已暂停' : (state.isFocus ? '专注中...' : '休息中...');
                    fullscreenStatus.style.color = state.isPaused ? '#888' : (state.isFocus ? '#e74c3c' : '#27ae60');
                }

                // 更新进度圈
                if (fullscreenProgressCircle) {
                    const circumference = 2 * Math.PI * 45;
                    if (state.isUpTimer) {
                        fullscreenProgressCircle.style.stroke = '#28a745';
                        fullscreenProgressCircle.style.strokeDashoffset = '0';
                    } else if (state.initialSeconds > 0) {
                        const progressPercent = ((state.initialSeconds - state.remainSeconds) / state.initialSeconds) * 100;
                        const dashoffset = circumference - (circumference * progressPercent / 100);
                        fullscreenProgressCircle.style.strokeDashoffset = dashoffset;

                        if (state.isFocus) {
                            fullscreenProgressCircle.style.stroke = '#e74c3c';
                        } else {
                            fullscreenProgressCircle.style.stroke = '#27ae60';
                        }
                    }
                }
            }
        }, 1000);

        // 进入全屏模式
        if (fullscreenContainer.requestFullscreen) {
            fullscreenContainer.requestFullscreen().catch(err => {
                console.error('全屏请求失败:', err);
                // 如果全屏失败，仍然显示内容
                document.body.appendChild(fullscreenContainer);
            });
        } else if (fullscreenContainer.webkitRequestFullscreen) { /* Safari */
            fullscreenContainer.webkitRequestFullscreen().catch(err => {
                console.error('Safari全屏请求失败:', err);
                document.body.appendChild(fullscreenContainer);
            });
        } else if (fullscreenContainer.msRequestFullscreen) { /* IE11 */
            fullscreenContainer.msRequestFullscreen().catch(err => {
                console.error('IE全屏请求失败:', err);
                document.body.appendChild(fullscreenContainer);
            });
        } else {
            console.warn('浏览器不支持全屏API，将以普通模式显示');
            document.body.appendChild(fullscreenContainer);
        }
    } catch (error) {
        console.error('全屏模式出现错误:', error);
        // 发生错误时显示提示
        showToast('全屏模式启动失败，将以普通模式显示', 'error');
    }
}

// 退出全屏
function exitFullscreen() {
    // 先移除全屏容器
    const fullscreenContainer = document.querySelector('.pomodoro-fullscreen');
    if (fullscreenContainer) {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }

        // 清除全屏更新定时器
        if (state.fullscreenUpdateInterval) {
            clearInterval(state.fullscreenUpdateInterval);
            state.fullscreenUpdateInterval = null;
        }

        // 直接移除全屏容器
        document.body.removeChild(fullscreenContainer);
    }
}

// 加载统计数据
function loadPomodoroStats() {
    const stats = JSON.parse(localStorage.getItem('pomodoroStats') || '{}');
    const today = new Date().toLocaleDateString();

    if (stats.lastDate !== today) {
        state.totalFocusTimeToday = 0;
        state.completedPomodoros = 0;
    } else {
        state.totalFocusTimeToday = stats.todayFocusTime || 0;
        state.completedPomodoros = stats.todayCompleted || 0;
    }

    state.totalCompletedPomodoros = stats.totalCompleted || 0;
    state.streakDays = stats.streakDays || 0;
    state.lastCompletedDate = stats.lastDate;
}


// 创建新的番茄记录
function createPomodoroRecord(startTime, endTime, duration, type) {
    return {
        id: 'pomodoro-' + Date.now(), // 唯一标识符
        startTime: startTime.toISOString(), // 开始时间，包含年月日时分秒
        endTime: endTime.toISOString(),     // 结束时间，包含年月日时分秒
        duration: Math.ceil(duration/60),       // 持续时间（分钟）
        type: type,                         // 类型：'timedown' 或 'timeup'
        timestamp: new Date().toISOString() // 创建时间戳
    };
}
// 保存番茄记录
function savePomodoroRecords(record) {
    // 获取当前的番茄记录列表
    const records = JSON.parse(localStorage.getItem('pomodoro_records') || '[]');
    // 添加新的记录
    records.push(record);
    // 保存更新后的记录列表
    localStorage.setItem('pomodoro_records', JSON.stringify(records));
}
// 保存统计数据
function savePomodoroStats() {
    const stats = {
        lastDate: new Date().toLocaleDateString(),
        todayFocusTime: state.totalFocusTimeToday,
        todayCompleted: state.completedPomodoros,
        totalCompleted: state.totalCompletedPomodoros,
        streakDays: state.streakDays
    };
    localStorage.setItem('pomodoroStats', JSON.stringify(stats));
}

// 更新设置
function updateSettings() {
    // 从输入框获取值并转换为数字
    const focusValue = parseInt(DOM_ELEMENTS.inputs.focus.value) || 25;
    const breakValue = parseInt(DOM_ELEMENTS.inputs.break.value) || 5;
    const longBreakValue = parseInt(DOM_ELEMENTS.inputs.longBreak.value) || 15;
    const pomodorosValue = parseInt(DOM_ELEMENTS.inputs.pomodorosUntilLongBreak.value) || 4;

    // 更新state对象
    state.focusDuration = focusValue * 60; // 转换为秒
    state.breakDuration = breakValue * 60; // 转换为秒
    state.longBreakDuration = longBreakValue * 60; // 转换为秒
    state.pomodorosUntilLongBreak = pomodorosValue;

    // 如果当前没有运行中的番茄钟，则更新显示
    if (!state.pomodoroInterval) {
        state.remainSeconds = state.focusDuration;
        state.initialSeconds = state.focusDuration;
        updateDisplay();
    }

    console.log('设置已更新:', {
        专注时长: focusValue,
        休息时长: breakValue,
        长休息时长: longBreakValue,
        番茄数量: pomodorosValue
    });
}

// 导出模块
module.exports = {
    initPomodoro
};